package MyFilter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "myFilter" , value = "/*")
public class MyFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //强转
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        //创建请求路径
        String path=httpServletRequest.getServletPath();
        //获取Session对象
        //如果是登录页面,验证码页面,和最终页面,注册页面,则放行
        if(path.equals("/login.jsp")||path.equals("/CaptchaCreate")||path.equals("/Login")||path.equals("/register.jsp")||path.equals("/Register")||path.equals("/homepage.jsp")){
            chain.doFilter(request, response);
        }else{
            HttpSession session=httpServletRequest.getSession();

            //Cookie校检
            //如果Session中有username,password,nickname,则有登录状态,放行
            if(session.getAttribute("username")!=null&&session.getAttribute("password")!=null&&session.getAttribute("nickname")!=null){
                chain.doFilter(request, response);
            }else{
                //如果没有登录状态,则尝试在Cookie中获取username,password,nickname如果能获取到则验证凭证放行,否则重定向到登录页面
                //创建Cookie数组(为遍历要获取的cookie做准备)
                Cookie[] cookies=httpServletRequest.getCookies();
                for (Cookie cookie : cookies){
                    //为了验证获取的cookie是否是我们需要的,我们可以判断cookie的名称是否是username,password,nickname
                    if(cookie.getValue()!=null&&cookie.getName().equals("nickname")){
                        //如果能获取到username,password,nickname,则验证凭证放行
                        //为了防止页面从session中获取不到username,password,nickname,我们需要再一次将其存入session中
                        //此时存入的是客户端的cookie值,而不是服务器的session值,所以需要注意安全性
//                        session.setAttribute("username",cookie.getValue());
//                        session.setAttribute("password",cookie.getValue());
                        session.setAttribute("nickname",cookie.getValue());
                        //存完后放行
                        chain.doFilter(request, response);
                        //放行后直接return即可,不用再执行后续代码
                        return;
                    }
                }
                //如果遍历完cookie都没有找到username,password,nickname,则重定向到登录页面
                request.setAttribute("error","请先登录");
                httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login.jsp");
            }
        }
    }
}
